package ru.spb.osll.myfit.server.handler;

import java.io.File;

import org.apache.log4j.Logger;

import ru.spb.osll.myfit.common.Content;
import ru.spb.osll.myfit.common.TreeNode;
import ru.spb.osll.myfit.server.parser.PageUtils;
import ru.spb.osll.myfit.util.FileHelper;

public class ContentCreator {
  private FileHelper m_helper = new FileHelper();

  private static Logger log = Logger.getLogger(ContentCreator.class);
  public void setHelper(FileHelper helper) {
    m_helper = helper;
  }

  public Content createContent(String fitnesseRoot, String pagePath, Integer lv) {
    String fullPath = PageUtils.getFullPathToContent(fitnesseRoot, pagePath);
    
    Content content = new Content(lv);
    content.setPath(pagePath);
    
    File file = m_helper.getFile(fullPath);  
    
    TreeNode root = shareChilds(file.getParentFile(), lv.intValue());
    content.setTreeNode(root);
    
    return content;
  }

  private TreeNode shareChilds(File parent, int depth) {
 //   boolean isPage = false;
    TreeNode root = new TreeNode(parent.getName());
    log.debug("ShareChilds ");
    
    File files[] = m_helper.listFiles(parent);
    if(files == null){
      return root;
    }
      
    for (File file : files) {
      if(m_helper.isDirectory(file)){
        root.setHasChild(true);
        if(depth > 0){
          TreeNode child = shareChilds(file, depth-1);
          root.addChildNode(child);
        }
      }
//        if ((m_helper.isDirectory(file))&&(depth>=0)) {
//          TreeNode child = shareChilds(file, depth-1);
//          if (child != null) {
//            root.hasChild();
//            if (depth>0)
//              root.addChildNode(child);
//          }
//        }
    }
 //   log.debug("ShareChilds isPage == " + isPage);
    return root;
  }
}

